package com.yxy.service.impl;

import com.yxy.exception.PasswordErrorException;
import com.yxy.exception.UserAlreadyExistsException;
import com.yxy.exception.UserNotFoundException;
import com.yxy.mapper.UserMapper;
import com.yxy.pojo.dto.UserDTO;
import com.yxy.pojo.dto.UserInfoDTO;
import com.yxy.pojo.entity.User;
import com.yxy.pojo.vo.UserInfoVO;
import com.yxy.pojo.vo.UserVO;
import com.yxy.service.UserService;
import com.yxy.utils.RandomNickNameUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @Override
    public UserVO login(UserDTO userDTO) {
        User u = userMapper.selectByUserName(userDTO.getUsername());
        if(u == null){
            throw new UserNotFoundException("用户不存在");
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        UserVO vo = userMapper.login(user);
        if(vo == null){
            throw new PasswordErrorException("密码错误");
        }
        return vo;
    }

    /**
     * 用户注册
     * @param userDTO
     */
    @Override
    public void register(UserDTO userDTO) {
        User u = userMapper.selectByUserName(userDTO.getUsername());
        if(u != null){
            throw new UserAlreadyExistsException("用户已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setNickName(RandomNickNameUtil.generateRandomNickName());
        user.setCreateTime(LocalDate.now());
        userMapper.insert(user);
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoVO getByUserId(int userId) {
        User user = userMapper.getById(userId);
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }

    /**
     * 更新用户信息
     * @param userInfoDTO
     */
    @Override
    public void updateUserInfo(UserInfoDTO userInfoDTO) {
        User user = new User();
        BeanUtils.copyProperties(userInfoDTO, user);
        userMapper.update(user);
    }

    /**
     * 校验密码
     * @param userInfoDTO
     * @return
     */
    @Override
    public Boolean checkPwd(UserInfoDTO userInfoDTO) {
        User user = new User();
        BeanUtils.copyProperties(userInfoDTO, user);
        return userMapper.checkPwd(user);
    }
}
